<?php
/**
 * 前台登录 退出操作
 *
 *
 *
 *
 * @copyright  Copyright (c) 2014-2015 TuntronKJ Inc. (http://www.tuntron.com)
 * @license    http://www.tuntron.com
 * @link       http://www.tuntron.com
 * @since      File available since Release v1.1
 */
defined('InTuntronKJ') or exit('Access Invalid!');

class loginControl extends BaseHomeControl {

	public function __construct(){
		parent::__construct();
	}

	/**
	 * 登录操作
	 *
	 */
	public function indexOp(){
		Language::read("home_login_index");
		$lang	= Language::getLangContent();
		$model_member	= Model('member');
		//检查登录状态
		$model_member->checkloginMember();

		$result = chksubmit(true,true,'num');

		if ($result !== false){
			
			if ($result === -11){

				$output = json_encode("freeze");
				echo $output;
				exit();
				
			}elseif ($result === -12){
				$output = json_encode("verCodefail");
				echo $output;
				exit();
			}
			if (processClass::islock('login')) {
				$output = json_encode("freeze");
				echo $output;
				exit();
			}
			$obj_validate = new Validate();
			$obj_validate->validateparam = array(
				array("input"=>$_POST["user_name"],		"require"=>"true", "message"=>$lang['login_index_username_isnull']),
				array("input"=>$_POST["password"],		"require"=>"true", "message"=>$lang['login_index_password_isnull']),
			);
			$error = $obj_validate->validate();
			if ($error != ''){
				showValidateError($error);exit;
			}
			$array	= array();
			$array['username']	= $_POST['username'];
			$array['password']	= md5($_POST['password']);
			$member_info = $model_member->infoMember($array);
			if(is_array($member_info) and !empty($member_info)) {
				if(!$member_info['enable']||$member_info['isDelete']){
			        $output = json_encode("freeze");
					echo $output;
					exit();
				}
			}else{
			    processClass::addprocess('login');
			    $output = json_encode("fail");
				echo $output;
				exit();
			}
    		$model_member->createSession($member_info);
			processClass::clear('login');
			//会员登录成功
			$output = json_encode("suc");
			echo $output;
			exit();

		}else{

			//登录表单页面
			$_pic = @unserialize(C('login_pic'));
			if ($_pic[0] != ''){
				Tpl::output('lpic',UPLOAD_SITE_URL.'/'.ATTACH_LOGIN.'/'.$_pic[array_rand($_pic)]);
			}else{
				Tpl::output('lpic',UPLOAD_SITE_URL.'/'.ATTACH_LOGIN.'/'.rand(1,4).'.jpg');
			}

			if(empty($_GET['ref_url'])) {
			    $ref_url = getReferer();
			    if (!preg_match('/ac=login&op=logout/', $ref_url)) {
			     $_GET['ref_url'] = $ref_url;
			    }
			}

			Tpl::output('html_title',C('site_name').' - '.$lang['login_index_login']);

			Tpl::showpage('login');
		}
	}

	/**
	 * 退出操作
	 *
	 * @param int $id 记录ID
	 * @return array $rs_row 返回数组形式的查询结果
	 */
	public function logoutOp(){
		$model_member = Model('member');
		print_r($_SESSION['uid']);
		$model_member->updateSession(array('isOnLine'=>0),$_SESSION['uid']);
		session_unset();
		session_destroy();

		if(empty($_GET['ref_url'])){
			$ref_url = getReferer();
		}else {
			$ref_url = $_GET['ref_url'];
		}
		@header("location: index.php?ac=login&ref_url=".urlencode($ref_url));
	}
	
	
	/**
	 * 找回密码发邮件至邮箱
	 * 
	 * @param
	 * @return
	 */
	public function find_passwordOp(){

		$model_member	= Model('member');
		$username = $_POST['userName'];
		$email = $_POST['email'];

		$memberinfo = $model_member->getMemberInfo(array('username'=>$username));

		if(!empty($memberinfo) && is_array($memberinfo)){
			if(strtoupper($memberinfo['email']) == strtoupper($email)){
				//用户名和邮箱正确，返回邮箱,并发送邮件至邮箱
				$data['email'] = $email;
				//将用户uid与日期进行合并加密				
				$data['token'] = encrypt($memberinfo['uid'].'|'.time());				
				$output = json_encode($data);	
			}else{			
				$data['email'] = "fail";
				$output = json_encode($data);
			}
		}else{
			$data['email'] = "fail";
			$output = json_encode($data);
		}
		echo $output;
		exit();
	}
	
	
	public function changepwOp(){

		$token = $_GET['token'];

		Tpl::output('token',$token);
		Tpl::showpage('changepw');
	}
	
	/**
	 * 重置用户登录密码
	 * 
	 */
	public function ChangePasswordByTokenOp(){

		$urlshang = $_SERVER['HTTP_REFERER']; //上一页URL
		$urldan = $_SERVER['SERVER_NAME']; //本站域名
		$urlcheck=substr($urlshang,7,strlen($urldan));
		if($urlcheck<>$urldan){
			Re_json_encode('-100','数据包被篡改，请重新操作!');
		}
		
		$token = $_POST['userToken'];
		$newPwd1 = $_POST['password'];
		$newPwd2 = $_POST['confirmPassword'];
		
		if(!$token) $output = json_encode("数据被篡改，请重新操作");	
			
		$data = explode('|',decrypt($token));

		$model_member = Model('member');
		$memberinfo = $model_member->getMemberInfo(array('uid'=>$data[0]));

		if(!$newPwd1){
			$output = json_encode("新密码不能为空！");
		}elseif($newPwd1 != $newPwd2){
			$output = json_encode("密码不一致，请重新输入!");
		}else{
			$update = $model_member->updateMember(array('password'=>md5($newPwd1)),$memberinfo['uid']);
			if($update){
				$output = json_encode("suc");
			}else{
				$output = json_encode("修改密码失败，请重新输入");
			}
				
		}
		echo $output;
		exit();

	}
	
	/**
	 * 电子邮箱检测
	 *
	 * @param
	 * @return
	 */
	public function check_emailOp() {
		$model_member = Model('member');
		$check_member_email	= $model_member->infoMember(array('member_email'=>trim($_GET['email'])));
		if(is_array($check_member_email) and count($check_member_email)>0) {
			echo 'false';
		} else {
			echo 'true';
		}
	}
	
	
	/**
	 * 异步发送邮件
	 */
	public function send_emailOp($d='') {
		Model('member')->checkloginMember();
	
		$model_cron = Model('cron');
		$condition = array();
		$condition['type'] = 2;
		$condition['exeid'] = $_SESSION['member_id'];
		$condition['code'] = 'email_touser_find_password';
		$cron_info = $model_cron->getCronInfo();
		if($d) $cron_info=$d;
		if (empty($cron_info)) return ;
	
		$content = unserialize($cron_info['content']);
		if (!$content[1]) $content[1] = false;
	
		$this->send_notice($cron_info['exeid'],$cron_info['code'],$content[0],$content[1]);
		$model_cron->delCron($condition);
	}
	
	/**
	 * 推广链接注册
	 */
	public function registerOp(){		
		$user_model = Model('member');
		$link_model = Model('link');
		$type = $_GET['type'];

		if(!$type){
			$token = $_GET['token'];
			$data = explode('|',decrypt($token));
			$username = $data[0];
			$linkid = $data[1];
			if($linkid){
				Tpl::output('username',$username);
				Tpl::output('linkid',$linkid);
			}else{
				Tpl::output('error',"推广链接失效");
			}
		}
		
		Tpl::output('type',$type);
		Tpl::showpage('register');
	}
	
	/**
	 * 注册会员
	 */
	public function userSaveOp(){
		$user_model = Model('member');
		$link_model = Model('link');
		$param_model = Model('params');

		$param['username'] = $_POST['Username'];
		$param['password'] = md5($_POST['UserPassword']);
		$param['email'] = $_POST['Email'];
		$param['regIP']= getIp();
		$param['regTime']= time();
		
		if(!$_POST['nickname']) $param['nickname']=$param['username'];
		if(!$_POST['name']) $param['name']=$param['username'];
				
		$linkId = $_POST['LinkId'];						//推广ID
		$intrCookie = $_POST['IntrCookie'];				//推广人
		$vercode = $_POST['ecv3'];						//验证码
		
		$user_info = $user_model->getMemberInfo(array('username'=>$intrCookie));
		$user_link = $link_model->getLinkInfo(array('lid'=>$linkId));
		$paraminfo = $param_model->getParamsInfo(array('name'=>'fanDianDiff'));			//上下级最小返点差
		
		$rule = "/^[A-Za-z\x{4e00}-\x{9fa5}][A-Za-z0-9\x{4e00}-\x{9fa5}]{1,19}$/u";			//用户名正则检验
		preg_match($rule, $param['username'],$result);
		$passlen=strlen($_POST['UserPassword']);
				
		//接收参数检查
		if(!$user_link){
			Re_json_encode('error','推广链接失效!');
		}else{
			$param['fanDian'] = floatval($user_link['fanDian']);
			$param['fanDianBdw'] = floatval($user_link['fanDianBdw']);
			$param['type'] = $user_link['type'];
			$param['parentId']= $user_link['uid'];
			$param['parents']= $userinfo['parents'];
		}
		
		if($user_info['uid'] != $user_link['uid']) Re_json_encode('error','推广链接失效!');
		if(!$param['username']) Re_json_encode('error','用户名不能为空!');
		if($param['fanDian']<0) Re_json_encode('error','返点不能小于0!');
		if($param['fanDianBdw']<0) Re_json_encode('error','不定位返点不能小于0!');
		
		if($param['fanDian'] > ($user_info['fanDian'] -$paraminfo['value']))
			Re_json_encode('error',"返点不能大于".($user_info['fanDian'] -$paraminfo['value'])."!");
		if($param['fanDianBdw'] > ($user_info['fanDianBdw'] -$paraminfo['value']))
			Re_json_encode('error',"不定位返点不能大于".($user_info['fanDian'] -$paraminfo['value'])."!");
		if($param['fanDian']){
			if(($param['fanDian']*100) % ($paraminfo['value']*100)){
				Re_json_encode('error',sprintf('返点只能是%.1f的倍数', $paraminfo['value']));
			}
		}
		
		if($param['type']!=0 && $param['type']!=1) Re_json_encode('error','会员类型出错!');
		if($passlen<6 || $passlen>16) Re_json_encode('error','密码长度不合法!');
		if(!$result[0]) Re_json_encode('error','用户名不合法，请重新填写!');
		
		$user_model->beginTransaction();
		try{
			$member = $user_model->getMemberInfo(array('username'=>$param['username']));
			if(!empty($member) && is_array($member)) Re_json_encode('error','用户名已被使用!');
		
			$id = $user_model->addMember($param);
			if($id){
				$parents = $user_info['parents'].','.$id;
				$user_model->updateMember(array('parents'=>$parents),$id);
				$user_model->commit();
				Re_json_encode('success','注册会员成功!');
			}else{
				Re_json_encode('error','注册会员失败!');
			}
		}catch(Exception $e){
			$user_model->rollBack();
			Re_json_encode('error','注册会员失败!');
		}
	}

}
